/*
 * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.security.web.servletapi;

import java.security.Principal;
import java.util.Collection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.Assert;

/**
 SecurityContextHolderAwareRequest
 Wrapper 类主要实现了 Servlet 3.0 之前和安全管理相关的三个方法，也就是 getRemoteUser()、
 isUserInRole(String) 以及 getUserPrincipal()。
 *
 * <ul>
 * <li>{@link #getUserPrincipal()}</li>
 * <li>{@link SecurityContextHolderAwareRequestWrapper#isUserInRole(String)}</li>
 * <li>{@link HttpServletRequestWrapper#getRemoteUser()}.</li>
 * </ul>
 *
 * @see SecurityContextHolderAwareRequestFilter
 *
 * @author Orlando Garcia Carmona
 * @author Ben Alex
 * @author Luke Taylor
 * @author Rob Winch
 */
public class SecurityContextHolderAwareRequestWrapper extends HttpServletRequestWrapper {
	// ~ Instance fields
	// ================================================================================================

	private final AuthenticationTrustResolver trustResolver;

	/**
	 * The prefix passed by the filter. It will be prepended to any supplied role values
	 * before comparing it with the roles obtained from the security context.
	 */
	private final String rolePrefix;

	// ~ Constructors
	// ===================================================================================================

	/**
	 * Creates a new instance with {@link AuthenticationTrustResolverImpl}.
	 *
	 * @param request
	 * @param rolePrefix
	 */
	public SecurityContextHolderAwareRequestWrapper(HttpServletRequest request,
			String rolePrefix) {
		this(request, new AuthenticationTrustResolverImpl(), rolePrefix);
	}

	/**
	 * Creates a new instance
	 *
	 * @param request the original {@link HttpServletRequest}
	 * @param trustResolver the {@link AuthenticationTrustResolver} to use. Cannot be
	 * null.
	 * @param rolePrefix The prefix to be added to {@link #isUserInRole(String)} or null
	 * if no prefix.
	 */
	public SecurityContextHolderAwareRequestWrapper(HttpServletRequest request,
			AuthenticationTrustResolver trustResolver, String rolePrefix) {
		super(request);
		Assert.notNull(trustResolver, "trustResolver cannot be null");
		this.rolePrefix = rolePrefix;
		this.trustResolver = trustResolver;
	}

	// ~ Methods
	// ========================================================================================================

	/**
	 * 该方法用来获取当前登录对象 Authentication，获取方式就是我们
	 * 前面所讲的从 SecurityContextHolder 中获取。如果不是匿名对象就返回，否则就返回 null。
	 *
	 * @return the authentication object or <code>null</code>
	 */
	private Authentication getAuthentication() {
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();

		if (!trustResolver.isAnonymous(auth)) {
			return auth;
		}

		return null;
	}

	/**
	 * 该方法返回了当前登录用户的用户名，如果 Authentication 对象中
	 * 存储的 Principal 是当前登录用户对象，则返回用户名；如果 Authentication 对象中存储的
	 * Principal 是当前登录用户名（字符串），则直接返回即可。
	 *
	 * @return the username or <code>null</code> if unavailable
	 */
	@Override
	public String getRemoteUser() {
		Authentication auth = getAuthentication();

		if ((auth == null) || (auth.getPrincipal() == null)) {
			return null;
		}

		if (auth.getPrincipal() instanceof UserDetails) {
			return ((UserDetails) auth.getPrincipal()).getUsername();
		}

		return auth.getPrincipal().toString();
	}

	/**
	 * 该方法返回当前登录用户对象，其实就是 Authentication 的实例。
	 * @return the <code>Authentication</code>, or <code>null</code>
	 */
	@Override
	public Principal getUserPrincipal() {
		Authentication auth = getAuthentication();

		if ((auth == null) || (auth.getPrincipal() == null)) {
			return null;
		}

		return auth;
	}

	/*
	该方法是一个私有方法，作用是判断当前登录用户是否具备某一个指定的角色。
	判断逻辑也很简单，先对传入进来的角色进行预处理，有的情况下可能需要添加ROLE_前缀，
	角色前缀的问题在本书后面的章节中会做详细介绍，这里先不做过多的展开。
然后调用 Authentication#getAuthorities 方法，获取当前登录用户所具备的所有角色，最后再和
传入进来的参数进行比较。
	 */
	private boolean isGranted(String role) {
		Authentication auth = getAuthentication();

		if (rolePrefix != null && role != null && !role.startsWith(rolePrefix)) {
			role = rolePrefix + role;
		}

		if ((auth == null) || (auth.getPrincipal() == null)) {
			return false;
		}

		Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();

		if (authorities == null) {
			return false;
		}

		for (GrantedAuthority grantedAuthority : authorities) {
			if (role.equals(grantedAuthority.getAuthority())) {
				return true;
			}
		}

		return false;
	}

	/**
	 * 该方法调用 isGranted 方法，进而实现判断当前用户是否具备某一个指定角色的功能。
	 * @param role the <code>GrantedAuthority</code><code>String</code> representation to
	 * check for
	 *
	 * @return <code>true</code> if an <b>exact</b> (case sensitive) matching granted
	 * authority is located, <code>false</code> otherwise
	 */
	@Override
	public boolean isUserInRole(String role) {
		return isGranted(role);
	}

	@Override
	public String toString() {
		return "SecurityContextHolderAwareRequestWrapper[ " + getRequest() + "]";
	}
}
